package com.winning.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestABCAlternate {

    public static void main(String[] args) {
        final int i = 20;
        final AlternateDemo ad = new AlternateDemo();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < i; j++) {
                    ad.loopA(j);
                }
            }
        },"A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < i; j++) {
                    ad.loopB(j);
                }
            }
        },"B").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < i; j++) {
                    ad.loopC(j);
                }
            }
        },"C").start();
    }

}

class AlternateDemo{

    private int number = 1;
    private Lock lock = new ReentrantLock();


    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void loopA(int num){
        lock.lock();
        try{

            if(number != 1){
                condition1.await();
            }

            System.out.println(Thread.currentThread().getName() + " : " + num);
            number = 2;
            condition2.signalAll();

        } catch (InterruptedException e) {
        } finally {
            lock.unlock();
        }
    }

    public void loopB(int num){
        lock.lock();
        try{

            if(number != 2){
                condition2.await();
            }

            System.out.println(Thread.currentThread().getName() + " : " + num);
            number = 3;
            condition3.signalAll();

        } catch (InterruptedException e) {
        } finally {
            lock.unlock();
        }
    }

    public void loopC(int num){
        lock.lock();
        try{

            if(number != 3){
                condition3.await();
            }

            System.out.println(Thread.currentThread().getName() + " : " + num);
            number = 1;
            condition1.signalAll();

        } catch (InterruptedException e) {
        } finally {
            lock.unlock();
        }
    }

}
